package com.zxm.edu.controller;
import com.zxm.edu.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * 通用请求处理
 *
 * @author silence.Z
 */
@RestController
public class CommonController {
	private static final Logger log = LoggerFactory.getLogger(CommonController.class);
	@Value("${upload.local.path}")
	private String localPath;
	@Value("${upload.local.url}")
	private String localUrl;

	/**
	 * 通用上传请求
	 */
	@PostMapping("/common/upload")
	public Result<?> uploadFile(MultipartFile file) throws Exception {
		try {
			// 上传文件路径
			// 上传并返回新文件名称
			System.out.println(localPath);
			String fileName = upload(localPath, file);
			String url = localUrl + fileName;
			System.out.println(url);
			HashMap<String, Object> map = new HashMap<>();
			map.put("fileName", fileName);
			map.put("url", url);
			return Result.ok(map);
		} catch (Exception e) {
			return Result.fail(e.getMessage());
		}
	}

	public String upload(String baseDir, MultipartFile file)
			throws Exception {
		int fileNamelength = file.getOriginalFilename().length();
		if (fileNamelength > 100) {
			throw new Exception("100");
		}

		//assertAllowed(file, allowedExtension);

		return extractFilename(file);
	}

	/**
	 * 编码文件名
	 */
	public String extractFilename(MultipartFile file)
	{
		String fileName = file.getOriginalFilename();
		/*String extension = "mp4";
		fileName = fileName + "." + extension;*/
		return fileName;
	}
	public File getAbsoluteFile(String uploadDir, String fileName) throws IOException
	{
		File desc = new File(uploadDir + File.separator + fileName);

		if (!desc.exists())
		{
			if (!desc.getParentFile().exists())
			{
				desc.getParentFile().mkdirs();
			}
		}
		return desc;
	}
	public String substring(final String str, int start) {
		if (str == null) {
			return "";
		}

		if (start < 0) {
			start = str.length() + start;
		}

		if (start < 0) {
			start = 0;
		}
		if (start > str.length()) {
			return "";
		}

		return str.substring(start);
	}
}
